home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 5 / BBS in a Box -Volume V (BBS in a Box) (April 1992).iso / Files / Prog / M / MPWGCC (Misc).cpt / Bison / Documents / Info / bison.info-1 next >
Encoding:
Text File  |  1989-05-30  |  48.4 KB  |  1,191 lines  |  [TEXT/MPS ]

  1. Info file bison.info, produced by Makeinfo, -*- Text -*- from input
  2. file bison.texinfo.
  3.  
  4. This file documents the Bison parser generator.
  5.  
  6. Copyright (C) 1988, 1989 Free Software Foundation, Inc.
  7.  
  8. Permission is granted to make and distribute verbatim copies of this
  9. manual provided the copyright notice and this permission notice are
  10. preserved on all copies.
  11.  
  12. Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the sections entitled ``GNU General Public License'' and
  15. ``Conditions for Using Bison'' are included exactly as in the
  16. original, and provided that the entire resulting derived work is
  17. distributed under the terms of a permission notice identical to this
  18. one.
  19.  
  20. Permission is granted to copy and distribute translations of this
  21. manual into another language, under the above conditions for modified
  22. versions, except that the sections entitled ``GNU General Public
  23. License'', ``Conditions for Using Bison'' and this permission notice
  24. may be included in translations approved by the Free Software
  25. Foundation instead of in the original English.
  26.  
  27.  
  28. 
  29. File: bison.info,  Node: Top,  Next: Introduction,  Prev: (DIR),  Up: (DIR)
  30.  
  31. * Menu:
  32.  
  33. * Introduction::
  34. * Conditions::
  35. * Copying::           The GNU General Public License says
  36.                         how you can copy and share Bison
  37.  
  38. Tutorial sections:
  39. * Concepts::          Basic concepts for understanding Bison.
  40. * Examples::          Three simple explained examples of using Bison.
  41.  
  42. Reference sections:
  43. * Grammar File::      Writing Bison declarations and rules.
  44. * Interface::         C-language interface to the parser function `yyparse'.
  45. * Algorithm::         How the Bison parser works at run-time.
  46. * Error Recovery::    Writing rules for error recovery.
  47. * Context Dependency::What to do if your language syntax is too
  48.             messy for Bison to handle straightforwardly.
  49. * Debugging::         Debugging Bison parsers that parse wrong.
  50. * Invocation::        How to run Bison (to produce the parser source file).
  51. * Table of Symbols::  All the keywords of the Bison language are explained.
  52. * Glossary::          Basic concepts are explained.
  53. * Index::             Cross-references to the text.
  54.  
  55.  
  56. 
  57. File: bison.info,  Node: Introduction,  Next: Conditions,  Prev: Top,  Up: Top
  58.  
  59. Introduction
  60. ************
  61.  
  62. "Bison" is a general-purpose parser generator which converts a
  63. grammar description into a C program to parse that grammar.  Once you
  64. are proficient with Bison, you may use it to develop a wide range of
  65. language parsers, from those used in simple desk calculators to
  66. complex programming languages.
  67.  
  68. Bison is upward compatible with Yacc: all properly-written Yacc
  69. grammars ought to work with Bison with no change.  Anyone familiar
  70. with Yacc should be able to use Bison with little trouble.  You need
  71. to be fluent in C programming in order to use Bison or to understand
  72. this manual.
  73.  
  74. We begin with tutorial chapters that explain the basic concepts of
  75. using Bison and show three explained examples, each building on the
  76. last.  If you don't know Bison or Yacc, start by reading these
  77. chapters.  Reference chapters follow which describe specific aspects
  78. of Bison in detail.
  79.  
  80. Bison was basically written by Robert Corbett, and made
  81. Yacc-compatible by Richard Stallman.
  82.  
  83.  
  84. 
  85. File: bison.info,  Node: Conditions,  Next: Copying,  Prev: Introduction,  Up: Top
  86.  
  87. Conditions for Using Bison
  88. **************************
  89.  
  90. Bison grammars can be used only in programs that are free software. 
  91. This is in contrast to what happens with the GNU C compiler and the
  92. other GNU programming tools.
  93.  
  94. The reason Bison is special is that the output of the Bison
  95. utility--the Bison parser file--contains a verbatim copy of a sizable
  96. piece of Bison, which is the code for the `yyparse' function.  (The
  97. actions from your grammar are inserted into this function at one
  98. point, but the rest of the function is not changed.)
  99.  
  100. As a result, the Bison parser file is covered by the same copying
  101. conditions that cover Bison itself and the rest of the GNU system:
  102. any program containing it has to be distributed under the standard
  103. GNU copying conditions.
  104.  
  105. Occasionally people who would like to use Bison to develop
  106. proprietary programs complain about this.
  107.  
  108. We don't particularly sympathize with their complaints.  The purpose
  109. of the GNU project is to promote the right to share software and the
  110. practice of sharing software; it is a means of changing society.  The
  111. people who complain are planning to be uncooperative toward the rest
  112. of the world; why should they deserve our help in doing so?
  113.  
  114. However, it's possible that a change in these conditions might
  115. encourage computer companies to use and distribute the GNU system. 
  116. If so, then we might decide to change the terms on `yyparse' as a
  117. matter of the strategy of promoting the right to share.  Such a
  118. change would be irrevocable.  Since we stand by the copying
  119. permissions we have announced, we cannot withdraw them once given.
  120.  
  121. We mustn't make an irrevocable change hastily.  We have to wait until
  122. there is a complete GNU system and there has been time to learn how
  123. this issue affects its reception.
  124.  
  125.  
  126. 
  127. File: bison.info,  Node: Copying,  Next: Concepts,  Prev: Conditions,  Up: Top
  128.  
  129. GNU GENERAL PUBLIC LICENSE
  130. **************************
  131.  
  132.                         Version 1, February 1989
  133.  
  134.      Copyright (C) 1989 Free Software Foundation, Inc.
  135.      675 Mass Ave, Cambridge, MA 02139, USA
  136.      
  137.      Everyone is permitted to copy and distribute verbatim copies
  138.      of this license document, but changing it is not allowed.
  139.  
  140.  Preamble
  141. =========
  142.  
  143.   The license agreements of most software companies try to keep users
  144. at the mercy of those companies.  By contrast, our General Public
  145. License is intended to guarantee your freedom to share and change
  146. free software--to make sure the software is free for all its users. 
  147. The General Public License applies to the Free Software Foundation's
  148. software and to any other program whose authors commit to using it. 
  149. You can use it for your programs, too.
  150.  
  151.   When we speak of free software, we are referring to freedom, not
  152. price.  Specifically, the General Public License is designed to make
  153. sure that you have the freedom to give away or sell copies of free
  154. software, that you receive source code or can get it if you want it,
  155. that you can change the software or use pieces of it in new free
  156. programs; and that you know you can do these things.
  157.  
  158.   To protect your rights, we need to make restrictions that forbid
  159. anyone to deny you these rights or to ask you to surrender the rights.
  160. These restrictions translate to certain responsibilities for you if
  161. you distribute copies of the software, or if you modify it.
  162.  
  163.   For example, if you distribute copies of a such a program, whether
  164. gratis or for a fee, you must give the recipients all the rights that
  165. you have.  You must make sure that they, too, receive or can get the
  166. source code.  And you must tell them their rights.
  167.  
  168.   We protect your rights with two steps: (1) copyright the software,
  169. and (2) offer you this license which gives you legal permission to
  170. copy, distribute and/or modify the software.
  171.  
  172.   Also, for each author's protection and ours, we want to make certain
  173. that everyone understands that there is no warranty for this free
  174. software.  If the software is modified by someone else and passed on,
  175. we want its recipients to know that what they have is not the
  176. original, so that any problems introduced by others will not reflect
  177. on the original authors' reputations.
  178.  
  179.   The precise terms and conditions for copying, distribution and
  180. modification follow.
  181.  
  182.                           TERMS AND CONDITIONS
  183.  
  184.   1. This License Agreement applies to any program or other work
  185.      which contains a notice placed by the copyright holder saying it
  186.      may be distributed under the terms of this General Public
  187.      License.  The ``Program'', below, refers to any such program or
  188.      work, and a ``work based on the Program'' means either the
  189.      Program or any work containing the Program or a portion of it,
  190.      either verbatim or with modifications.  Each licensee is
  191.      addressed as ``you''.
  192.  
  193.   2. You may copy and distribute verbatim copies of the Program's
  194.      source code as you receive it, in any medium, provided that you
  195.      conspicuously and appropriately publish on each copy an
  196.      appropriate copyright notice and disclaimer of warranty; keep
  197.      intact all the notices that refer to this General Public License
  198.      and to the absence of any warranty; and give any other
  199.      recipients of the Program a copy of this General Public License
  200.      along with the Program.  You may charge a fee for the physical
  201.      act of transferring a copy.
  202.  
  203.   3. You may modify your copy or copies of the Program or any portion
  204.      of it, and copy and distribute such modifications under the
  205.      terms of Paragraph 1 above, provided that you also do the
  206.      following:
  207.  
  208.         * cause the modified files to carry prominent notices stating
  209.           that you changed the files and the date of any change; and
  210.  
  211.         * cause the whole of any work that you distribute or publish,
  212.           that in whole or in part contains the Program or any part
  213.           thereof, either with or without modifications, to be
  214.           licensed at no charge to all third parties under the terms
  215.           of this General Public License (except that you may choose
  216.           to grant warranty protection to some or all third parties,
  217.           at your option).
  218.  
  219.         * If the modified program normally reads commands
  220.           interactively when run, you must cause it, when started
  221.           running for such interactive use in the simplest and most
  222.           usual way, to print or display an announcement including an
  223.           appropriate copyright notice and a notice that there is no
  224.           warranty (or else, saying that you provide a warranty) and
  225.           that users may redistribute the program under these
  226.           conditions, and telling the user how to view a copy of this
  227.           General Public License.
  228.  
  229.         * You may charge a fee for the physical act of transferring a
  230.           copy, and you may at your option offer warranty protection
  231.           in exchange for a fee.
  232.  
  233.      Mere aggregation of another independent work with the Program
  234.      (or its derivative) on a volume of a storage or distribution
  235.      medium does not bring the other work under the scope of these
  236.      terms.
  237.  
  238.   4. You may copy and distribute the Program (or a portion or
  239.      derivative of it, under Paragraph 2) in object code or
  240.      executable form under the terms of Paragraphs 1 and 2 above
  241.      provided that you also do one of the following:
  242.  
  243.         * accompany it with the complete corresponding
  244.           machine-readable source code, which must be distributed
  245.           under the terms of Paragraphs 1 and 2 above; or,
  246.  
  247.         * accompany it with a written offer, valid for at least three
  248.           years, to give any third party free (except for a nominal
  249.           charge for the cost of distribution) a complete
  250.           machine-readable copy of the corresponding source code, to
  251.           be distributed under the terms of Paragraphs 1 and 2 above;
  252.           or,
  253.  
  254.         * accompany it with the information you received as to where
  255.           the corresponding source code may be obtained.  (This
  256.           alternative is allowed only for noncommercial distribution
  257.           and only if you received the program in object code or
  258.           executable form alone.)
  259.  
  260.      Source code for a work means the preferred form of the work for
  261.      making modifications to it.  For an executable file, complete
  262.      source code means all the source code for all modules it
  263.      contains; but, as a special exception, it need not include
  264.      source code for modules which are standard libraries that
  265.      accompany the operating system on which the executable file
  266.      runs, or for standard header files or definitions files that
  267.      accompany that operating system.
  268.  
  269.   5. You may not copy, modify, sublicense, distribute or transfer the
  270.      Program except as expressly provided under this General Public
  271.      License.  Any attempt otherwise to copy, modify, sublicense,
  272.      distribute or transfer the Program is void, and will
  273.      automatically terminate your rights to use the Program under
  274.      this License.  However, parties who have received copies, or
  275.      rights to use copies, from you under this General Public License
  276.      will not have their licenses terminated so long as such parties
  277.      remain in full compliance.
  278.  
  279.   6. By copying, distributing or modifying the Program (or any work
  280.      based on the Program) you indicate your acceptance of this
  281.      license to do so, and all its terms and conditions.
  282.  
  283.   7. Each time you redistribute the Program (or any work based on the
  284.      Program), the recipient automatically receives a license from
  285.      the original licensor to copy, distribute or modify the Program
  286.      subject to these terms and conditions.  You may not impose any
  287.      further restrictions on the recipients' exercise of the rights
  288.      granted herein.
  289.  
  290.   8. The Free Software Foundation may publish revised and/or new
  291.      versions of the General Public License from time to time.  Such
  292.      new versions will be similar in spirit to the present version,
  293.      but may differ in detail to address new problems or concerns.
  294.  
  295.      Each version is given a distinguishing version number.  If the
  296.      Program specifies a version number of the license which applies
  297.      to it and ``any later version'', you have the option of
  298.      following the terms and conditions either of that version or of
  299.      any later version published by the Free Software Foundation.  If
  300.      the Program does not specify a version number of the license,
  301.      you may choose any version ever published by the Free Software
  302.      Foundation.
  303.  
  304.   9. If you wish to incorporate parts of the Program into other free
  305.      programs whose distribution conditions are different, write to
  306.      the author to ask for permission.  For software which is
  307.      copyrighted by the Free Software Foundation, write to the Free
  308.      Software Foundation; we sometimes make exceptions for this.  Our
  309.      decision will be guided by the two goals of preserving the free
  310.      status of all derivatives of our free software and of promoting
  311.      the sharing and reuse of software generally.
  312.  
  313.                                    NO WARRANTY
  314.  
  315.  10. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  316.      WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  317.      LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  318.      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS''
  319.      WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
  320.      INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  321.      MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE
  322.      ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS
  323.      WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE
  324.      COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  325.  
  326.  11. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  327.      WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  328.      MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  329.      LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  330.      INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  331.      INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS
  332.      OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
  333.      YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH
  334.      ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  335.      ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  336.  
  337.                       END OF TERMS AND CONDITIONS
  338.  
  339. Appendix: How to Apply These Terms to Your New Programs
  340. =======================================================
  341.  
  342.   If you develop a new program, and you want it to be of the greatest
  343. possible use to humanity, the best way to achieve this is to make it
  344. free software which everyone can redistribute and change under these
  345. terms.
  346.  
  347.   To do so, attach the following notices to the program.  It is safest
  348. to attach them to the start of each source file to most effectively
  349. convey the exclusion of warranty; and each file should have at least
  350. the ``copyright'' line and a pointer to where the full notice is found.
  351.  
  352.      ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
  353.      Copyright (C) 19YY  NAME OF AUTHOR
  354.      
  355.      This program is free software; you can redistribute it and/or modify
  356.      it under the terms of the GNU General Public License as published by
  357.      the Free Software Foundation; either version 1, or (at your option)
  358.      any later version.
  359.      
  360.      This program is distributed in the hope that it will be useful,
  361.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  362.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  363.      GNU General Public License for more details.
  364.      
  365.      You should have received a copy of the GNU General Public License
  366.      along with this program; if not, write to the Free Software
  367.      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  368.  
  369.  Also add information on how to contact you by electronic and paper
  370. mail.
  371.  
  372. If the program is interactive, make it output a short notice like
  373. this when it starts in an interactive mode:
  374.  
  375.      Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  376.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
  377.      This is free software, and you are welcome to redistribute it
  378.      under certain conditions; type `show c' for details.
  379.  
  380.  The hypothetical commands `show w' and `show c' should show the
  381. appropriate parts of the General Public License.  Of course, the
  382. commands you use may be called something other than `show w' and
  383. `show c'; they could even be mouse-clicks or menu items--whatever
  384. suits your program.
  385.  
  386. You should also get your employer (if you work as a programmer) or
  387. your school, if any, to sign a ``copyright disclaimer'' for the
  388. program, if necessary.  Here a sample; alter the names:
  389.  
  390.      Yoyodyne, Inc., hereby disclaims all copyright interest in the
  391.      program `Gnomovision' (a program to direct compilers to make passes
  392.      at assemblers) written by James Hacker.
  393.      
  394.      SIGNATURE OF TY COON, 1 April 1989
  395.      Ty Coon, President of Vice
  396.  
  397. That's all there is to it!
  398.  
  399.  
  400. 
  401. File: bison.info,  Node: Concepts,  Next: Examples,  Prev: Copying,  Up: Top
  402.  
  403. The Concepts of Bison
  404. *********************
  405.  
  406. This chapter introduces many of the basic concepts without which the
  407. details of Bison will not make sense.  If you do not already know how
  408. to use Bison or Yacc, we suggest you start by reading this chapter
  409. carefully.
  410.  
  411. * Menu:
  412.  
  413. * Language and Grammar::  Languages and context-free grammars,
  414.                 as mathematical ideas.
  415. * Grammar in Bison::      How we represent grammars for Bison's sake.
  416. * Semantic Values::       Each token or syntactic grouping can have
  417.                             a semantic value (the value of an integer,
  418.                             the name of an identifier, etc.).
  419. * Semantic Actions::      Each rule can have an action containing C code.
  420. * Bison Parser::          What are Bison's input and output,
  421.                             how is the output used?
  422. * Stages::          Stages in writing and running Bison grammars.
  423. * Grammar Layout::        Overall structure of a Bison grammar file.
  424.  
  425.  
  426. 
  427. File: bison.info,  Node: Language and Grammar,  Next: Grammar in Bison,  Prev: Concepts,  Up: Concepts
  428.  
  429. Languages and Context-Free Grammars
  430. ===================================
  431.  
  432. In order for Bison to parse a language, it must be described by a
  433. "context-free grammar".  This means that you specify one or more
  434. "syntactic groupings" and give rules for constructing them from their
  435. parts.  For example, in the C language, one kind of grouping is
  436. called an `expression'.  One rule for making an expression might be,
  437. ``An expression can be made of a minus sign and another expression''.
  438. Another would be, ``An expression can be an integer''.  As you can
  439. see, rules are often recursive, but there must be at least one rule
  440. which leads out of the recursion.
  441.  
  442. The most common formal system for presenting such rules for humans to
  443. read is "Backus-Naur Form" or ``BNF'', which was developed in order
  444. to specify the language Algol 60.  Any grammar expressed in BNF is a
  445. context-free grammar.  The input to Bison is essentially
  446. machine-readable BNF.
  447.  
  448. In the formal grammatical rules for a language, each kind of
  449. syntactic unit or grouping is named by a "symbol".  Those which are
  450. built by grouping smaller constructs according to grammatical rules
  451. are called "nonterminal symbols"; those which can't be subdivided are
  452. called "terminal symbols" or "token types".  We call a piece of input
  453. corresponding to a single terminal symbol a "token", and a piece
  454. corresponding to a single nonterminal symbol a "grouping".
  455.  
  456. We can use the C language as an example of what symbols, terminal and
  457. nonterminal, mean.  The tokens of C are identifiers, constants
  458. (numeric and string), and the various keywords, arithmetic operators
  459. and punctuation marks.  So the terminal symbols of a grammar for C
  460. include `identifier', `number', `string', plus one symbol for each
  461. keyword, operator or punctuation mark: `if', `return', `const',
  462. `static', `int', `char', `plus-sign', `open-brace', `close-brace',
  463. `comma' and many more.  (These tokens can be subdivided into
  464. characters, but that is a matter of lexicography, not grammar.)
  465.  
  466. Here is a simple C function subdivided into tokens:
  467.  
  468.      int             /* keyword `int' */
  469.      square (x)      /* identifier, open-paren, */
  470.                      /* identifier, close-paren */
  471.           int x;     /* keyword `int', identifier, semicolon */
  472.      {               /* open-brace */
  473.        return x * x; /* keyword `return', identifier, */
  474.                      /* asterisk, identifier, semicolon */
  475.      }               /* close-brace */
  476.  
  477. The syntactic groupings of C include the expression, the statement,
  478. the declaration, and the function definition.  These are represented
  479. in the grammar of C by nonterminal symbols `expression', `statement',
  480. `declaration' and `function definition'.  The full grammar uses
  481. dozens of additional language constructs, each with its own
  482. nonterminal symbol, in order to express the meanings of these four. 
  483. The example above is a function definition; it contains one
  484. declaration, and one statement.  In the statement, each `x' is an
  485. expression and so is `x * x'.
  486.  
  487. Each nonterminal symbol must have grammatical rules showing how it is
  488. made out of simpler constructs.  For example, one kind of C statement
  489. is the `return' statement; this would be described with a grammar
  490. rule which reads informally as follows:
  491.  
  492.      A `statement' can be made of a `return' keyword, an `expression'
  493.      and a `semicolon'.
  494.  
  495. There would be many other rules for `statement', one for each kind of
  496. statement in C.
  497.  
  498. One nonterminal symbol must be distinguished as the special one which
  499. defines a complete utterance in the language.  It is called the
  500. "start symbol".  In a compiler, this means a complete input program. 
  501. In the C language, the nonterminal symbol `sequence of definitions
  502. and declarations' plays this role.
  503.  
  504. For example, `1 + 2' is a valid C expression--a valid part of a C
  505. program--but it is not valid as an *entire* C program.  In the
  506. context-free grammar of C, this follows from the fact that
  507. `expression' is not the start symbol.
  508.  
  509. The Bison parser reads a sequence of tokens as its input, and groups
  510. the tokens using the grammar rules.  If the input is valid, the end
  511. result is that the entire token sequence reduces to a single grouping
  512. whose symbol is the grammar's start symbol.  If we use a grammar for
  513. C, the entire input must be a `sequence of definitions and
  514. declarations'.  If not, the parser reports a syntax error.
  515.  
  516.  
  517. 
  518. File: bison.info,  Node: Grammar in Bison,  Next: Semantic Values,  Prev: Language and Grammar,  Up: Concepts
  519.  
  520. From Formal Rules to Bison Input
  521. ================================
  522.  
  523. A formal grammar is a mathematical construct.  To define the language
  524. for Bison, you must write a file expressing the grammar in Bison
  525. syntax: a "Bison grammar" file.  *Note Grammar File::.
  526.  
  527. A nonterminal symbol in the formal grammar is represented in Bison
  528. input as an identifier, like an identifier in C.  By convention, it
  529. should be in lower case, such as `expr', `stmt' or `declaration'.
  530.  
  531. The Bison representation for a terminal symbol is also called a
  532. "token type".  Token types as well can be represented as C-like
  533. identifiers.  By convention, these identifiers should be upper case
  534. to distinguish them from nonterminals: for example, `INTEGER',
  535. `IDENTIFIER', `IF' or `RETURN'.  A terminal symbol that stands for a
  536. particular keyword in the language should be named after that keyword
  537. converted to upper case.  The terminal symbol `error' is reserved for
  538. error recovery.  *Note Symbols::.
  539.  
  540. A terminal symbol can also be represented as a character literal,
  541. just like a C character constant.  You should do this whenever a
  542. token is just a single character (parenthesis, plus-sign, etc.): use
  543. that same character in a literal as the terminal symbol for that token.
  544.  
  545. The grammar rules also have an expression in Bison syntax.  For
  546. example, here is the Bison rule for a C `return' statement.  The
  547. semicolon in quotes is a literal character token, representing part
  548. of the C syntax for the statement; the naked semicolon, and the
  549. colon, are Bison punctuation used in every rule.
  550.  
  551.      stmt:   RETURN expr ';'
  552.              ;
  553.  
  554. *Note Rules::.
  555.  
  556.  
  557. 
  558. File: bison.info,  Node: Semantic Values,  Next: Semantic Actions,  Prev: Grammar in Bison,  Up: Concepts
  559.  
  560. Semantic Values
  561. ===============
  562.  
  563. A formal grammar selects tokens only by their classifications: for
  564. example, if a rule mentions the terminal symbol `integer constant',
  565. it means that *any* integer constant is grammatically valid in that
  566. position.  The precise value of the constant is irrelevant to how to
  567. parse the input: if `x+4' is grammatical then `x+1' or `x+3989' is
  568. equally grammatical.
  569.  
  570. But the precise value is very important for what the input means once
  571. it is parsed.  A compiler is useless if it fails to distinguish
  572. between 4, 1 and 3989 as constants in the program!  Therefore, each
  573. token in a Bison grammar has both a token type and a "semantic
  574. value".  *Note Semantics::, for details.
  575.  
  576. The token type is a terminal symbol defined in the grammar, such as
  577. `INTEGER_CONSTANT', `IDENTIFIER' or `',''.  It tells everything you
  578. need to know to decide where the token may validly appear and how to
  579. group it with other tokens.  The grammar rules know nothing about
  580. tokens except their types.
  581.  
  582. The semantic value has all the the rest of the information about the
  583. meaning of the token, such as the value of an integer, or the name of
  584. an identifier.  (A token such as `','' which is just punctuation
  585. doesn't need to have any semantic value.)
  586.  
  587. For example, an input token might be classified as token type
  588. `INTEGER' and have the semantic value 4.  Another input token might
  589. have the same token type `INTEGER' but value 3989.  When a grammar
  590. rule says that `INTEGER' is allowed, either of these tokens is
  591. acceptable because each is an `INTEGER'.  When the parser accepts the
  592. token, it keeps track of the token's semantic value.
  593.  
  594. Each grouping can also have a semantic value as well as its
  595. nonterminal symbol.  For example, in a calculator, an expression
  596. typically has a semantic value that is a number.  In a compiler for a
  597. programming language, an expression typically has a semantic value
  598. that is a tree structure describing the meaning of the expression.
  599.  
  600.  
  601. 
  602. File: bison.info,  Node: Semantic Actions,  Next: Bison Parser,  Prev: Semantic Values,  Up: Concepts
  603.  
  604. Semantic Actions
  605. ================
  606.  
  607. In order to be useful, a program must do more than parse input; it
  608. must also produce some output based on the input.  In a Bison
  609. grammar, a grammar rule can have an "action" made up of C statements.
  610. Each time the parser recognizes a match for that rule, the action is
  611. executed.  *Note Actions::.       Most of the time, the purpose
  612. of an action is to compute the semantic value of the whole construct
  613. from the semantic values of its parts.  For example, suppose we have
  614. a rule which says an expression can be the sum of two expressions. 
  615. When the parser recognizes such a sum, each of the subexpressions has
  616. a semantic value which describes how it was built up.  The action for
  617. this rule should create a similar sort of value for the newly
  618. recognized larger expression.
  619.  
  620. For example, here is a rule that says an expression can be the sum of
  621. two subexpressions:
  622.  
  623.      expr: expr '+' expr   { $$ = $1 + $3; }
  624.              ;
  625.  
  626. The action says how to produce the semantic value of the sum
  627. expression from the values of the two subexpressions.
  628.  
  629.  
  630. 
  631. File: bison.info,  Node: Bison Parser,  Next: Stages,  Prev: Semantic Actions,  Up: Concepts
  632.  
  633. Bison Output: the Parser File
  634. =============================
  635.  
  636. When you run Bison, you give it a Bison grammar file as input.  The
  637. output is a C source file that parses the language described by the
  638. grammar.  This file is called a "Bison parser".  Keep in mind that
  639. the Bison utility and the Bison parser are two distinct programs: the
  640. Bison utility is a program whose output is the Bison parser that
  641. becomes part of your program.
  642.  
  643. The job of the Bison parser is to group tokens into groupings
  644. according to the grammar rules--for example, to build identifiers and
  645. operators into expressions.  As it does this, it runs the actions for
  646. the grammar rules it uses.
  647.  
  648. The tokens come from a function called the "lexical analyzer" that
  649. you must supply in some fashion (such as by writing it in C).  The
  650. Bison parser calls the lexical analyzer each time it wants a new
  651. token.  It doesn't know what is ``inside'' the tokens (though their
  652. semantic values may reflect this).  Typically the lexical analyzer
  653. makes the tokens by parsing characters of text, but Bison does not
  654. depend on this.  *Note Lexical::.
  655.  
  656. The Bison parser file is C code which defines a function named
  657. `yyparse' which implements that grammar.  This function does not make
  658. a complete C program: you must supply some additional functions.  One
  659. is the lexical analyzer.  Another is an error-reporting function
  660. which the parser calls to report an error.  In addition, a complete C
  661. program must start with a function called `main'; you have to provide
  662. this, and arrange for it to call `yyparse' or the parser will never
  663. run.  *Note Interface::.
  664.  
  665. Aside from the token type names and the symbols in the actions you
  666. write, all variable and function names used in the Bison parser file
  667. begin with `yy' or `YY'.  This includes interface functions such as
  668. the lexical analyzer function `yylex', the error reporting function
  669. `yyerror' and the parser function `yyparse' itself.  This also
  670. includes numerous identifiers used for internal purposes.  Therefore,
  671. you should avoid using C identifiers starting with `yy' or `YY' in
  672. the Bison grammar file except for the ones defined in this manual.
  673.  
  674.  
  675. 
  676. File: bison.info,  Node: Stages,  Next: Grammar Layout,  Prev: Bison Parser,  Up: Concepts
  677.  
  678. Stages in Using Bison
  679. =====================
  680.  
  681. The actual language-design process using Bison, from grammar
  682. specification to a working compiler or interpreter, has these parts:
  683.  
  684.   1. Formally specify the grammar in a form recognized by Bison
  685.      (*note Grammar File::.).  For each grammatical rule in the
  686.      language, describe the action that is to be taken when an
  687.      instance of that rule is recognized.  The action is described by
  688.      a sequence of C statements.
  689.  
  690.   2. Write a lexical analyzer to process input and pass tokens to the
  691.      parser.  The lexical analyzer may be written by hand in C (*note
  692.      Lexical::.).  It could also be produced using Lex, but the use
  693.      of Lex is not discussed in this manual.
  694.  
  695.   3. Write a controlling function that calls the Bison-produced parser.
  696.  
  697.   4. Write error-reporting routines.
  698.  
  699. To turn this source code as written into a runnable program, you must
  700. follow these steps:
  701.  
  702.   1. Run Bison on the grammar to produce the parser.
  703.  
  704.   2. Compile the code output by Bison, as well as any other source
  705.      files.
  706.  
  707.   3. Link the object files to produce the finished product.
  708.  
  709.  
  710. 
  711. File: bison.info,  Node: Grammar Layout,  Prev: Stages,  Up: Concepts
  712.  
  713. The Overall Layout of a Bison Grammar
  714. =====================================
  715.  
  716. The input file for the Bison utility is a "Bison grammar file".  The
  717. general form of a Bison grammar file is as follows:
  718.  
  719.      %{
  720.      C DECLARATIONS
  721.      %}
  722.      
  723.      BISON DECLARATIONS
  724.      
  725.      %%
  726.      GRAMMAR RULES
  727.      %%
  728.      ADDITIONAL C CODE
  729.  
  730. The `%%', `%{' and `%}' are punctuation that appears in every Bison
  731. grammar file to separate the sections.
  732.  
  733. The C declarations may define types and variables used in the actions.
  734. You can also use preprocessor commands to define macros used there,
  735. and use `#include' to include header files that do any of these things.
  736.  
  737. The Bison declarations declare the names of the terminal and
  738. nonterminal symbols, and may also describe operator precedence and
  739. the data types of semantic values of various symbols.
  740.  
  741. The grammar rules define how to construct each nonterminal symbol
  742. from its parts.
  743.  
  744. The additional C code can contain any C code you want to use.  Often
  745. the definition of the lexical analyzer `yylex' goes here, plus
  746. subroutines called by the actions in the grammar rules.  In a simple
  747. program, all the rest of the program can go here.
  748.  
  749.  
  750. 
  751. File: bison.info,  Node: Examples,  Next: Grammar File,  Prev: Concepts,  Up: Top
  752.  
  753. Examples
  754. ********
  755.  
  756. Now we show and explain three sample programs written using Bison: a
  757. reverse polish notation calculator, an algebraic (infix) notation
  758. calculator, and a multi-function calculator.  All three have been
  759. tested under BSD Unix 4.3; each produces a usable, though limited,
  760. interactive desk-top calculator.
  761.  
  762. These examples are simple, but Bison grammars for real programming
  763. languages are written the same way.
  764.  
  765. You can copy these examples out of the Info file and into a source
  766. file to try them.
  767.  
  768. * Menu:
  769.  
  770. * RPN Calc::               Reverse polish notation calculator;
  771.                  a first example with no operator precedence.
  772. * Infix Calc::           Infix (algebraic) notation calculator.
  773.                  Operator precedence is introduced.
  774. * Simple Error Recovery::  Continuing after syntax errors.
  775. * Multi-function Calc::    Calculator with memory and trig functions.
  776.                  It uses multiple data-types for semantic values.
  777. * Exercises::           Ideas for improving the multi-function calculator.
  778.  
  779.  
  780. 
  781. File: bison.info,  Node: RPN Calc,  Next: Infix Calc,  Prev: Examples,  Up: Examples
  782.  
  783. Reverse Polish Notation Calculator
  784. ==================================
  785.  
  786. The first example is that of a simple double-precision "reverse
  787. polish notation" calculator (a calculator using postfix operators). 
  788. This example provides a good starting point, since operator
  789. precedence is not an issue.  The second example will illustrate how
  790. operator precedence is handled.
  791.  
  792. The source code for this calculator is named `rpcalc.y'.  The `.y'
  793. extension is a convention used for Bison input files.
  794.  
  795. * Menu:
  796.  
  797. * Decls: Rpcalc Decls.    Bison and C declarations for rpcalc.
  798. * Rules: Rpcalc Rules.    Grammar Rules for rpcalc, with explanation.
  799. * Input: Rpcalc Input.      Explaining the rules for `input'.
  800. * Line: Rpcalc Line.      Explaining the rules for `line'.
  801. * Expr: Rpcalc Expr.      Explaining the rules for `expr'.
  802. * Lexer: Rpcalc Lexer.    The lexical analyzer.
  803. * Main: Rpcalc Main.      The controlling function.
  804. * Error: Rpcalc Error.    The error reporting function.
  805. * Gen: Rpcalc Gen.        Running Bison on the grammar file.
  806. * Comp: Rpcalc Compile.   Run the C compiler on the output code.
  807.  
  808.  
  809. 
  810. File: bison.info,  Node: Rpcalc Decls,  Next: Rpcalc Rules,  Prev: RPN calc,  Up: RPN calc
  811.  
  812. Declarations for Rpcalc
  813. -----------------------
  814.  
  815. Here are the C and Bison declarations for the reverse polish notation
  816. calculator.  As in C, comments are placed between `/*...*/'.
  817.  
  818.      /* Reverse polish notation calculator. */
  819.      
  820.      %{
  821.      #define YYSTYPE double
  822.      #include <math.h>
  823.      %}
  824.      
  825.      %token NUM
  826.      
  827.      %% /* Grammar rules and actions follow */
  828.  
  829. The C declarations section (*note C Declarations::.) contains two
  830. preprocessor directives.
  831.  
  832. The `#define' directive defines the macro `YYSTYPE', thus specifying
  833. the C data type for semantic values of both tokens and groupings
  834. (*note Value Type::.).  The Bison parser will use whatever type
  835. `YYSTYPE' is defined as; if you don't define it, `int' is the
  836. default.  Because we specify `double', each token and each expression
  837. has an associated value, which is a floating point number.
  838.  
  839. The `#include' directive is used to declare the exponentiation
  840. function `pow'.
  841.  
  842. The second section, Bison declarations, provides information to Bison
  843. about the token types (*note Bison Declarations::.).  Each terminal
  844. symbol that is not a single-character literal must be declared here. 
  845. (Single-character literals normally don't need to be declared.)  In
  846. this example, all the arithmetic operators are designated by
  847. single-character literals, so the only terminal symbol that needs to
  848. be declared is `NUM', the token type for numeric constants.
  849.  
  850.  
  851. 
  852. File: bison.info,  Node: Rpcalc Rules,  Next: Rpcalc Input,  Prev: Rpcalc Decls,  Up: RPN Calc
  853.  
  854. Grammar Rules for Rpcalc
  855. ------------------------
  856.  
  857. Here are the grammar rules for the reverse polish notation calculator.
  858.  
  859.      input:    /* empty */
  860.              | input line
  861.      ;
  862.      
  863.      line:     '\n'
  864.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  865.      ;
  866.      
  867.      exp:      NUM             { $$ = $1;         }
  868.              | exp exp '+'     { $$ = $1 + $2;    }
  869.              | exp exp '-'     { $$ = $1 - $2;    }
  870.              | exp exp '*'     { $$ = $1 * $2;    }
  871.              | exp exp '/'     { $$ = $1 / $2;    }
  872.            /* Exponentiation */
  873.              | exp exp '^'     { $$ = pow ($1, $2); }
  874.            /* Unary minus    */
  875.              | exp 'n'         { $$ = -$1;        }
  876.      ;
  877.      %%
  878.  
  879. The groupings of the rpcalc ``language'' defined here are the
  880. expression (given the name `exp'), the line of input (`line'), and
  881. the complete input transcript (`input').  Each of these nonterminal
  882. symbols has several alternate rules, joined by the `|' punctuator
  883. which is read as ``or''.  The following sections explain what these
  884. rules mean.
  885.  
  886. The semantics of the language is determined by the actions taken when
  887. a grouping is recognized.  The actions are the C code that appears
  888. inside braces.  *Note Actions::.
  889.  
  890. You must specify these actions in C, but Bison provides the means for
  891. passing semantic values between the rules.  In each action, the
  892. pseudo-variable `$$' stands for the semantic value for the grouping
  893. that the rule is going to construct.  Assigning a value to `$$' is
  894. the main job of most actions.  The semantic values of the components
  895. of the rule are referred to as `$1', `$2', and so on.
  896.  
  897.  
  898. 
  899. File: bison.info,  Node: Rpcalc Input,  Next: Rpcalc Line,  Prev: Rpcalc Rules,  Up: RPN Calc
  900.  
  901. Explanation of `input'
  902. ......................
  903.  
  904.  Consider the definition of `input':
  905.  
  906.      input:    /* empty */
  907.              | input line
  908.      ;
  909.  
  910. This definition reads as follows: ``A complete input is either an
  911. empty string, or a complete input followed by an input line''. 
  912. Notice that ``complete input'' is defined in terms of itself.  This
  913. definition is said to be "left recursive" since `input' appears
  914. always as the leftmost symbol in the sequence.  *Note Recursion::.
  915.  
  916. The first alternative is empty because there are no symbols between
  917. the colon and the first `|'; this means that `input' can match an
  918. empty string of input (no tokens).  We write the rules this way
  919. because it is legitimate to type `Ctrl-d' right after you start the
  920. calculator.  It's conventional to put an empty alternative first and
  921. write the comment `/* empty */' in it.
  922.  
  923. The second alternate rule (`input line') handles all nontrivial input.
  924. It means, ``After reading any number of lines, read one more line if
  925. possible.''  The left recursion makes this rule into a loop.  Since
  926. the first alternative matches empty input, the loop can be executed
  927. zero or more times.
  928.  
  929. The parser function `yyparse' continues to process input until a
  930. grammatical error is seen or the lexical analyzer says there are no
  931. more input tokens; we will arrange for the latter to happen at end of
  932. file.
  933.  
  934.  
  935. 
  936. File: bison.info,  Node: Rpcalc Line,  Next: Rpcalc Expr,  Prev: Rpcalc Input,  Up: RPN Calc
  937.  
  938. Explanation of `line'
  939. .....................
  940.  
  941.  Now consider the definition of `line':
  942.  
  943.      line:     '\n'
  944.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  945.      ;
  946.  
  947. The first alternative is a token which is a newline character; this
  948. means that rpcalc accepts a blank line (and ignores it, since there
  949. is no action).  The second alternative is an expression followed by a
  950. newline.  This is the alternative that makes rpcalc useful.  The
  951. semantic value of the `exp' grouping is the value of `$1' because the
  952. `exp' in question is the first symbol in the alternative.  The action
  953. prints this value, which is the result of the computation the user
  954. asked for.
  955.  
  956. This action is unusual because it does not assign a value to `$$'. 
  957. As a consequence, the semantic value associated with the `line' is
  958. uninitialized (its value will be unpredictable).  This would be a bug
  959. if that value were ever used, but we don't use it: once rpcalc has
  960. printed the value of the user's input line, that value is no longer
  961. needed.
  962.  
  963.  
  964. 
  965. File: bison.info,  Node: Rpcalc Expr,  Next: Rpcalc Lexer,  Prev: Rpcalc Line,  Up: RPN Calc
  966.  
  967. Explanation of `expr'
  968. .....................
  969.  
  970.  The `exp' grouping has several rules, one for each kind of expression.
  971. The first rule handles the simplest expressions: those that are just
  972. numbers.  The second handles an addition-expression, which looks like
  973. two expressions followed by a plus-sign.  The third handles
  974. subtraction, and so on.
  975.  
  976.      exp:      NUM
  977.              | exp exp '+'     { $$ = $1 + $2;    }
  978.              | exp exp '-'     { $$ = $1 - $2;    }
  979.              ...
  980.              ;
  981.  
  982. We have used `|' to join all the rules for `exp', but we could
  983. equally well have written them separately:
  984.  
  985.      exp:      NUM ;
  986.      exp:      exp exp '+'     { $$ = $1 + $2;    } ;
  987.      exp:      exp exp '-'     { $$ = $1 - $2;    } ;
  988.              ...
  989.  
  990.  Most of the rules have actions that compute the value of the
  991. expression in terms of the value of its parts.  For example, in the
  992. rule for addition, `$1' refers to the first component `exp' and `$2'
  993. refers to the second one.  The third component, `'+'', has no
  994. meaningful associated semantic value, but if it had one you could
  995. refer to it as `$3'.  When `yyparse' recognizes a sum expression
  996. using this rule, the sum of the two subexpressions' values is
  997. produced as the value of the entire expression.  *Note Actions::.
  998.  
  999. You don't have to give an action for every rule.  When a rule has no
  1000. action, Bison by default copies the value of `$1' into `$$'.  This is
  1001. what happens in the first rule (the one that uses `NUM').
  1002.  
  1003. The formatting shown here is the recommended convention, but Bison
  1004. does not require it.  You can add or change whitespace as much as you
  1005. wish.  For example, this:
  1006.  
  1007.      exp   : NUM | exp exp '+' {$$ = $1 + $2; } | ...
  1008.  
  1009.  means the same thing as this:
  1010.  
  1011.      exp:      NUM
  1012.              | exp exp '+'    { $$ = $1 + $2; }
  1013.              | ...
  1014.  
  1015.  The latter, however, is much more readable.
  1016.  
  1017.  
  1018. 
  1019. File: bison.info,  Node: Rpcalc Lexer,  Next: Rpcalc Main,  Prev: Rpcalc Expr,  Up: RPN Calc
  1020.  
  1021. The Rpcalc Lexical Analyzer
  1022. ---------------------------
  1023.  
  1024. The lexical analyzer's job is low-level parsing: converting
  1025. characters or sequences of characters into tokens.  The Bison parser
  1026. gets its tokens by calling the lexical analyzer.  *Note Lexical::.
  1027.  
  1028. Only a simple lexical analyzer is needed for the RPN calculator. 
  1029. This lexical analyzer skips blanks and tabs, then reads in numbers as
  1030. `double' and returns them as `NUM' tokens.  Any other character that
  1031. isn't part of a number is a separate token.  Note that the token-code
  1032. for such a single-character token is the character itself.
  1033.  
  1034. The return value of the lexical analyzer function is a numeric code
  1035. which represents a token type.  The same text used in Bison rules to
  1036. stand for this token type is also a C expression for the numeric code
  1037. for the type.  This works in two ways.  If the token type is a
  1038. character literal, then its numeric code is the ASCII code for that
  1039. character; you can use the same character literal in the lexical
  1040. analyzer to express the number.  If the token type is an identifier,
  1041. that identifier is defined by Bison as a C macro whose definition is
  1042. the appropriate number.  In this example, therefore, `NUM' becomes a
  1043. macro for `yylex' to use.
  1044.  
  1045. The semantic value of the token (if it has one) is stored into the
  1046. global variable `yylval', which is where the Bison parser will look
  1047. for it.  (The C data type of `yylval' is `YYSTYPE', which was defined
  1048. at the beginning of the grammar; *note Rpcalc Decls::..)
  1049.  
  1050. A token type code of zero is returned if the end-of-file is
  1051. encountered.  (Bison recognizes any nonpositive value as indicating
  1052. the end of the input.)
  1053.  
  1054. Here is the code for the lexical analyzer:
  1055.  
  1056.      /* Lexical analyzer returns a double floating point number on the
  1057.         stack and the token NUM, or the ASCII character read if not a
  1058.         number.  Skips all blanks and tabs, returns 0 for EOF. */
  1059.      
  1060.      #include <ctype.h>
  1061.      
  1062.      yylex ()
  1063.      {
  1064.        int c;
  1065.      
  1066.        while ((c = getchar ()) == ' ' || c == '\t')  /* skip white space  */
  1067.          ;
  1068.        if (c == '.' || isdigit (c))                /* process numbers   */
  1069.          {
  1070.            ungetc (c, stdin);
  1071.            scanf ("%lf", &yylval);
  1072.            return NUM;
  1073.          }
  1074.        if (c == EOF)                            /* return end-of-file  */
  1075.          return 0;
  1076.        return c;                                /* return single chars */
  1077.      }
  1078.  
  1079.  
  1080. 
  1081. File: bison.info,  Node: Rpcalc Main,  Next: Rpcalc Error,  Prev: Rpcalc Lexer,  Up: RPN Calc
  1082.  
  1083. The Controlling Function
  1084. ------------------------
  1085.  
  1086. In keeping with the spirit of this example, the controlling function
  1087. is kept to the bare minimum.  The only requirement is that it call
  1088. `yyparse' to start the process of parsing.
  1089.  
  1090.      main ()
  1091.      {
  1092.        yyparse ();
  1093.      }
  1094.  
  1095.  
  1096. 
  1097. File: bison.info,  Node: Rpcalc Error,  Next: Rpcalc Gen,  Prev: Rpcalc Main,  Up: RPN Calc
  1098.  
  1099. The Error Reporting Routine
  1100. ---------------------------
  1101.  
  1102. When `yyparse' detects a syntax error, it calls the error reporting
  1103. function `yyerror' to print an error message (usually but not always
  1104. `"parse error"').  It is up to the programmer to supply `yyerror'
  1105. (*note Interface::.), so here is the definition we will use:
  1106.  
  1107.      #include <stdio.h>
  1108.      
  1109.      yyerror (s)  /* Called by yyparse on error */
  1110.           char *s;
  1111.      {
  1112.        printf ("%s\n", s);
  1113.      }
  1114.  
  1115. After `yyerror' returns, the Bison parser may recover from the error
  1116. and continue parsing if the grammar contains a suitable error rule
  1117. (*note Error Recovery::.).  Otherwise, `yyparse' returns nonzero.  We
  1118. have not written any error rules in this example, so any invalid
  1119. input will cause the calculator program to exit.  This is not clean
  1120. behavior for a real calculator, but it is adequate in the first
  1121. example.
  1122.  
  1123.  
  1124. 
  1125. File: bison.info,  Node: Rpcalc Gen,  Next: Rpcalc Compile,  Prev: Rpcalc Error,  Up: RPN Calc
  1126.  
  1127. Running Bison to Make the Parser
  1128. --------------------------------
  1129.  
  1130. Before running Bison to produce a parser, we need to decide how to
  1131. arrange all the source code in one or more source files.  For such a
  1132. simple example, the easiest thing is to put everything in one file. 
  1133. The definitions of `yylex', `yyerror' and `main' go at the end, in
  1134. the ``additional C code'' section of the file (*note Grammar
  1135. Layout::.).
  1136.  
  1137. For a large project, you would probably have several source files,
  1138. and use `make' to arrange to recompile them.
  1139.  
  1140. With all the source in a single file, you use the following command
  1141. to convert it into a parser file:
  1142.  
  1143.      bison FILE_NAME.y
  1144.  
  1145. In this example the file was called `rpcalc.y' (for ``Reverse Polish
  1146. CALCulator'').  Bison produces a file named `FILE_NAME.tab.c',
  1147. removing the `.y' from the original file name. The file output by
  1148. Bison contains the source code for `yyparse'.  The additional
  1149. functions in the input file (`yylex', `yyerror' and `main') are
  1150. copied verbatim to the output.
  1151.  
  1152.  
  1153. 
  1154. File: bison.info,  Node: Rpcalc Compile,  Prev: Rpcalc Gen,  Up: RPN Calc
  1155.  
  1156. Compiling the Parser File
  1157. -------------------------
  1158.  
  1159. Here is how to compile and run the parser file:
  1160.  
  1161.      # List files in current directory.
  1162.      % ls
  1163.      rpcalc.tab.c  rpcalc.y
  1164.      
  1165.      # Compile the Bison parser.
  1166.      # `-lm' tells compiler to search math library for `pow'.
  1167.      % cc rpcalc.tab.c -lm -o rpcalc
  1168.      
  1169.      # List files again.
  1170.      % ls
  1171.      rpcalc  rpcalc.tab.c  rpcalc.y
  1172.  
  1173. The file `rpcalc' now contains the executable code.  Here is an
  1174. example session using `rpcalc'.
  1175.  
  1176.      % rpcalc
  1177.      4 9 +
  1178.      13
  1179.      3 7 + 3 4 5 *+-
  1180.      -13
  1181.      3 7 + 3 4 5 * + - n              Note the unary minus, `n'
  1182.      13
  1183.      5 6 / 4 n +
  1184.      -3.166666667
  1185.      3 4 ^                            Exponentiation
  1186.      81
  1187.      ^D                               End-of-file indicator
  1188.      %
  1189.  
  1190.  
  1191.